const { Doc, Dictionary } = require('../models');
const { Op } = require('sequelize');

class DocService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { title, category_id } = filter;
		const where = {};
		if (title) where['title'] = { [Op.like]: `%${title}%` };
		if (category_id) where['category_id'] = category_id;

		const { count: total, rows: data } = await Doc.findAndCountAll({
			where,
			include: {
				model: Dictionary,
				as: 'category',
				attributes: ['name']
			},

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'asc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		const doc = await Doc.findOne({
			where
		});

		doc.increment({ pv: 1 });

		return doc;
	}

	async delete(id) {
		const data = await Doc.findAll({
			where: {
				id: { [Op.in]: String(id).split(',') }
			}
		});

		data.forEach((doc) => {
			doc.destroy();
		})

		return true;
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		const { id } = params;

		if (id) {
			return await Doc.update(params, {
				where: {
					id
				}
			})
		} else {
			return await Doc.create(params);
		}
	}
}

exports = module.exports = DocService;
